package Model;

/**
 * 井字棋游戏核心逻辑类
 * 管理游戏状态和AI算法
 */
public class Board {

    //棋盘状态
    private final String[] state;
    //获胜逻辑
    private final int[][] WON = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
    private final int win = 100;
    private final int lose = -100;
    private final int draw = 0;

    public Board(){
        //使用9格字符串对应9个按钮
        state = new String[9];
        for (int i = 0; i < 9; i++) {
            // 初始化所有元素为空字符串
            state[i] = "";
        }
    }

    //按照按钮位置 存储 该位置的 字符串信息
    public void setState(int i,String s){
        state[i] = s;
    }

    /**
     * 判断当前游戏状态
     * @return 游戏结果常量: win(100)/lose(-100)/draw(0)/继续(1)
     */
    public int Judge(){
        
        int number = 0;
        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 3; j++) {
                if("X".equals(state[WON[i][j]])){
                    number++;
                }
                else if("O".equals(state[WON[i][j]])){
                    number--;
                }
            }
            if (number == 3){
                return win;
            } else if (number == -3) {
                return lose;
            }else {
                number = 0;
            }
        }
        for (int i = 0; i < 9; i++) {
            if (state[i].isEmpty()){
                return 1;
            }
        }
        return draw;
    }

    public int getWin() {
        return win;
    }

    public int getLose() {
        return lose;
    }

    public int getDraw() {
        return draw;
    }

    public String[] getState() {
        return state;
    }
}
